package com.hdax.dmw.user.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hdax.dmw.common.exception.DmwException;
import com.hdax.dmw.common.exception.user.LoginException;
import com.hdax.dmw.dtos.user.LoginDto;
import com.hdax.dmw.user.DmUser;
import com.hdax.dmw.user.mappers.DmUserMapper;
import com.hdax.dmw.user.service.UserLoginService;
import com.hdax.dmw.utils.Result;
import com.hdax.dmw.utils.ResultGenerator;
import com.hdax.dmw.utils.ServiceResultEnum;
import org.springframework.stereotype.Service;

@Service
public class UserLoginServiceImpl extends ServiceImpl<DmUserMapper, DmUser> implements UserLoginService {

    @Override
    public Result<LoginDto> login(String phone, String password) throws DmwException {
        if(phone == null || password == null){
            throw new LoginException(ServiceResultEnum.TOKEN_EXPIRE_ERROR);
        }
        //连接数据库查询
        QueryWrapper<DmUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        DmUser user = getOne(queryWrapper);
        if(user == null){
            throw new LoginException(ServiceResultEnum.LOGIN_NAME_IS_NOT_PHONE);
        }else{
            if(!user.getPassword().equals(SecureUtil.md5(password))){
                throw new LoginException(ServiceResultEnum.LOGIN_PASSWORD_ERROR);
            }
        }
        LoginDto dto = new LoginDto();
        dto.setToken("1234567");
        dto.setNickName(user.getNickName());
        dto.setGenTime(System.currentTimeMillis());
        dto.setExtTime(dto.getGenTime()+ 2 * 60 * 60 * 1000);
        return ResultGenerator.genSuccessResult(dto);
    }
}
